﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autocentro.Entities;
using System.Data.Objects;

namespace Autocentro.Respository
{
    public class ProveedorRepository :MasterRepository, IProveedorRepository
    {
        public List<PROVEEDOR> GetAllFromProveedores()
        {
            var query = from p in context.Proveedor
                        select p;

            ObjectContext.Refresh(RefreshMode.StoreWins, query);
            return query.ToList();
        }

        public List<PROVEEDOR> GetFromProveedorByCriterio(string criterio)
        {
            var query = from p in context.Proveedor
                        select p;
            if (criterio != null && criterio != string.Empty && criterio != "")
            {
                query = from p in query
                        where p.Ruc.ToUpper().Contains(criterio.ToUpper()) ||
                        p.RazonSocial.ToUpper().Contains(criterio.ToUpper())
                        select p;           
            }
            else
            {
                query = from p in query
                        select p;
            }

            ObjectContext.Refresh(RefreshMode.StoreWins, query);
            return query.ToList();
        }

        public PROVEEDOR GetFromProveedorById(int id)
        {
            return context.Proveedor.Find(id);
        }

        public void AddProveedor(PROVEEDOR proveedor)
        {
            context.Proveedor.Add(proveedor);
            context.SaveChanges();
        }

        public void UpdateProveedor(PROVEEDOR proveedor)
        {
            context.Entry(proveedor).State = System.Data.EntityState.Modified;
            context.SaveChanges();
        }

        public void RemoveProveedor(int id)
        {
            var existe = context.Proveedor.Find(id);
            if (existe!=null)
            {
                context.Proveedor.Remove(existe);
                context.SaveChanges();
            }
        }


        public bool eliminarDuplicidad(string ruc, string razonSocial, int id)
        {
            var query = from p in context.Proveedor
                        where (p.Ruc.ToUpper().CompareTo(ruc.ToUpper()) == 0 ||
                        p.RazonSocial.ToUpper().CompareTo(razonSocial.ToUpper()) == 0) &&
                        p.Id != id
                        select p;

            ObjectContext.Refresh(RefreshMode.StoreWins, query);
            return query.Any();
        }


        public PROVEEDOR GetFromProveedorByRuc(string ruc)
        {
            var query = from p in context.Proveedor
                        where p.Ruc.Equals(ruc)
                        select p;

            ObjectContext.Refresh(RefreshMode.StoreWins, query);

            return query.FirstOrDefault();
        }
    }
}
